﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Configuration;
using Bansud.SGR.CommonSGR;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Data.Linq;
using System.Web.UI;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace condortravel.operaciones.common
{
    public class Util
    {

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string getStringDateTimeNow()
        {
            return DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string getKeyAppSettingConfig(string key)
        {
            return ConfigurationSettings.AppSettings[key];
        }

        /// <summary>
        /// Load section appseting's configuration from web.config
        /// </summary>
        public static void LoadAppSettingToApplication(HttpApplicationState application)
        {
            try
            {
                String registry = (String)application[AppStatic.REGISTRO_CLAVE];
                if (registry != null)
                {
                    registry = ConfigurationSettings.AppSettings[AppStatic.REGISTRO_CLAVE];
                    SecurityEncrypt security = new SecurityEncrypt();
                    String x = Bansud.SGR.CommonSGR.SGRUtil.LeeRegistro(registry, AppStatic.CONNECTION_REGEDIT_CONDORTOPERACIONES);
                    application[AppStatic.CONNECTION_REGEDIT_CONDORTOPERACIONES] = security.Decrypt(Bansud.SGR.CommonSGR.SGRUtil.LeeRegistro(registry, AppStatic.CONNECTION_REGEDIT_CONDORTOPERACIONES));

                    application[AppStatic.CONNECTION_REGEDIT_CONDORTOPERACIONES_IMPERSONATE] = security.Decrypt(Bansud.SGR.CommonSGR.SGRUtil.LeeRegistro(registry, AppStatic.CONNECTION_REGEDIT_CONDORTOPERACIONES_IMPERSONATE));
                }
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }


        public static void SelectItemDropDownList(DropDownList list, string selectedItem)
        {
            foreach (ListItem p in list.Items)
                p.Selected=p.Value.Trim().Equals(selectedItem.Trim());


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="dataSource"></param>
        /// <param name="dataText"></param>
        /// <param name="dataValue"></param>
        public static void  LoadDropDownList(DropDownList obj, object dataSource, string dataText, string dataValue, bool insertItemEmpty,String defaultValue, String defaultText)
        {

            //Todo: Colocar Lock
            obj.DataSource = dataSource;
            obj.DataTextField = dataText;
            obj.DataValueField = dataValue;
            obj.DataBind();
            if (insertItemEmpty)
            {
                ListItem item = new ListItem();
                item.Value = defaultValue;
                item.Text = defaultText;
                item.Selected = true;
                obj.Items.Insert(0, item);
            }
        }
        public static bool IsContractor(string userName)
        {
            Regex r = new Regex("[a-zA-Z][a-zA-Z][a-zA-Z][9][9][9]");
            return r.IsMatch(userName);
            

        }
       

        public static void ExportGridView2excel(DataTable dtGrid)
        {
            HttpContext _ctx = HttpContext.Current;        

            StringBuilder sb = new StringBuilder();
            System.IO.StringWriter stringWrite = new System.IO.StringWriter(sb);
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            Page page = new Page();
            System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
            page.DesignerInitialize();
            page.Controls.Add(form);

            GridView gv1 = new GridView();
            //= GridView1

            gv1.AllowPaging = false;
            gv1.AllowSorting = false;
            gv1.DataSource = dtGrid;
            gv1.DataBind();
            gv1.EnableViewState = false;
            form.Controls.Add(gv1);
            page.RenderControl(htmlWrite);
            //gv1.RenderControl(htmlWrite)
            _ctx.Response.Clear();
            _ctx.Response.Buffer = true;
            //_ctx.Response.ContentType = "text/plain"
            //_ctx.Response.ContentType = "application/vnd.xls"
            _ctx.Response.ContentType = "application/vnd.ms-excel";
            _ctx.Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
            _ctx.Response.Charset = "UTF-8";
            _ctx.Response.ContentEncoding = Encoding.Default;

            _ctx.Response.Write(stringWrite.ToString());
            _ctx.Response.End();

        }

        public static DataTable toDataTable(DataContext dc, Object qr)
        {
            
            DataTable dt = new DataTable();
            IDbCommand cmd = dc.GetCommand(qr as IQueryable);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = (SqlCommand)cmd;
            cmd.Connection.Open();
            adapter.FillSchema(dt, SchemaType.Source);
            adapter.Fill(dt);
            cmd.Connection.Close();
            return dt;
        }
      
        public static Hashtable readConnectioRegedit(string ConnectionString)
        {
            Hashtable configTable = new Hashtable();

            try
            {
                int countString = ConnectionString.Length;
                List<int> commaArray = new List<int>();
                List<int> equalArray = new List<int>();

                for (int i = 0; i <= countString - 1; i++)
                {
                    if ((ConnectionString.Substring(i, 1) == ";"))
                    {
                        commaArray.Add(i);
                    }
                    else
                    {
                        if ((ConnectionString.Substring(i, 1) == "="))
                        {
                            equalArray.Add(i);
                        }
                    }
                }

                for (int i = 0; i <= commaArray.Count - 1; i++)
                {
                    int posicion = i;
                    int posicionAnterior = (i == 0 ? 0 : i - 1);

                    int inferior = (i == 0 ? 0 : commaArray[posicionAnterior]);
                    int superior = commaArray[posicion];
                    //Coma
                    int comma = 0;

                    foreach (int equal in equalArray)
                    {
                        if (equal > inferior & equal < superior)
                        {
                            comma = equal;
                        }
                    }

                    inferior = (inferior == 0 ? 0 : inferior + 1);

                    string key = ConnectionString.Substring(inferior, comma - inferior);
                    string value = ConnectionString.Substring(comma + 1, superior - comma - 1);

                    configTable.Add(key.Trim(), value.Trim());
                }


            }
            catch (Exception ex)
            {
            }

            return configTable;
        }

    }
}
